import React, { useEffect, useState } from "react";
import { getHttp, putHttp } from "../../../../api";
import { useRequest, useSetState } from "ahooks";
import style from "./style.module.scss";
import no_doctor from "../../../../assets/images/image/hdpi/doctor.png";
import nextIcon from "../../../../assets/images/icon/common resource/hdpi/common_information_next_n.png";
import DoctorDetailIcon from "../../../../assets/images/icon/common resource/hdpi/common_icon_more_n.png";
import sort_top from "../../../../assets/images/icon/common resource/hdpi/common_button_ascending_s.png";
import sort_bot from "../../../../assets/images/icon/common resource/hdpi/common_button_descending_s.png";
import { useNavigate } from "react-router-dom";
import { Empty, Notify } from "react-vant";
import { useDispatch } from "react-redux";
import { addDoctorList } from "../../../../store/doctorDetail/doctorDetailSlice";
import { MyHeader } from "../../../../components";
import { useAppSelector } from "../../../../store/hooks";

const Index: React.FC = () => {
  const userId = useAppSelector((state) => state.user.userInfo.userId);
  const sessionId = useAppSelector((state) => state.user.userInfo.sessionId);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  // 跳转医生详情页
  const goDoctorDetail = (doclist) => {
    console.log(doclist.doctorId);
    dispatch(addDoctorList(doclist.doctorId));
    navigate("/consultation/doctor/detail");
  };
  // const recordId = searchParams.get("recordId") as string;
  // const doctorName = searchParams.get("doctorName") as string;
  const getCurrentInquiryRecord = () =>
    getHttp(
      "/health/user/inquiry/verify/v1/findCurrentInquiryRecord",
      {
        userId,sessionId
      }
    )
  // 跳转聊天页
  const goChat = (doclist) => {
    const { doctorId, doctorName } = doclist;

    putHttp(
      `/health/user/inquiry/verify/v1/consultDoctor?doctorId=${doctorId}`
    ).then((res) => {
      if (res.status === "0000") {
        dispatch(addDoctorList(doctorId));
        getCurrentInquiryRecord().then((res) => {
          navigate(
            `/consultation/chat?doctorId=${doctorId}&doctorName=${doctorName}&recordId=${res.result.recordId}&imagePic=${res.result.imagePic}`
          );
        })
     
      } else {
        Notify.show({ message: res.message, type: "danger" });
      }
    });
  };

  // 医生列表
  const [infoDoctorListParams, setinfoDoctorListParams] = useSetState({
    deptId: 2,
    condition: 1,
    page: 1,
    count: 3,
    sortBy: 0 as number | null,
  });

  // 医生列表类型
  interface DoctorListRawState {
    deptId: number;
  }

  // 医生列表接口
  const getDoctorList = (params: DoctorListRawState) =>
    getHttp("/health/user/inquiry/v1/findDoctorList", params);
  const { data: DoctorList = [], run } = useRequest(async () => {
    const resp = await getDoctorList(infoDoctorListParams);
    return resp.result;
  });

  // tab导航接口
  const gettabNav = () =>
    getHttp("/health/share/knowledgeBase/v1/findDepartment");
  const { data: tabNav = [] } = useRequest(async () => {
    const resp = await gettabNav();
    return resp.result;
  });
  // tab切换事件
  const tabClick = (index) => {
    setinfoDoctorListParams({
      ...infoDoctorListParams,
      deptId: index,
    });
  };

  // 点击切换医生详细信息大图
  const [ind, setind] = useState(0);
  const DoctorDetailClick = (doctor) => {
    const items = DoctorList.forEach((v, i) => {
      if (v.doctorId == doctor.doctorId) {
        setind(i);
      }
    });
  };

  // 点击切换下一页
  const nextPageClick = () => {
    setinfoDoctorListParams({
      ...infoDoctorListParams,
      page: infoDoctorListParams.page + 1,
    });
  };

  // 排序
  const [active, setactive] = useState(0);
  const [state, setState] = useState(true);
  const sort = (i) => {
    i == 3 && setState(!state);
    setactive(i);
    setinfoDoctorListParams({
      ...infoDoctorListParams,
      condition: i + 1,
      sortBy: i == 3 ? (!state ? 1 : 2) : null,
    });
  };
  useEffect(() => {
    run();
  }, [infoDoctorListParams]);

  console.log(tabNav);

  return (
    <div className={style["box"]}>
      {/* <header className={style["header"]}>/头部/</header> */}
      <MyHeader title={<h3>医生列表</h3>}></MyHeader>

      {/* tab */}
      <div className={style["tabNav_top"]}>
        <div className={style["tabNav_top-items"]}>
          {tabNav.length > 0 &&
            tabNav.map((v, i) => (
              <span
                key={i}
                onClick={() => tabClick(v.id)}
                className={
                  infoDoctorListParams.deptId == v.id ? style["active"] : ""
                }
              >
                {v.departmentName}
              </span>
            ))}
        </div>
      </div>
      <div className={style["tabNav_bot"]}>
        {["综合", "好评", "咨询数", "价格"].map((v, i) => (
          <div key={i}>
            <span
              onClick={() => sort(i)}
              className={i == active ? style["active"] : ""}
            >
              {v}
            </span>
            {i == 3 ? (
              <img
                className={style["img"]}
                src={state ? sort_top : sort_bot}
                alt=""
              />
            ) : (
              ""
            )}
          </div>
        ))}
      </div>

      {/* 空状态 */}
      {DoctorList.length == 0 && (
        <Empty
          className="custom-image"
          imageSize={75}
          image={<img src={no_doctor} />}
          description="暂无医生数据"
        />
      )}

      {/* bigimg */}
      <div className={style["DoctorDetail"]}>
        {DoctorList.length > 0 && (
          <div className={style["detail"]}>
            <img src={DoctorList[ind].imagePic} alt="" />
            <div className={style["detail_con"]}>
              <p>
                <span className={style["DoctorName"]}>
                  {DoctorList[ind].doctorName}{" "}
                </span>
                <span>{DoctorList[ind].jobTitle}</span>{" "}
              </p>
              <p>
                {DoctorList[ind].inauguralHospital}{" "}
                <img
                  src={DoctorDetailIcon}
                  alt=""
                  className={style["doctordetailicon"]}
                  onClick={() => goDoctorDetail(DoctorList[ind])}
                />
              </p>
              <p>
                <span>好评率:{DoctorList[ind].praise}</span>{" "}
                <span>服务患者数量:{DoctorList[ind].serverNum}</span>
              </p>
              <p className={style["price"]}>
                <span>{DoctorList[ind].servicePrice}H币/次</span>
                <button onClick={() => goChat(DoctorList[ind])}>
                  立即咨询
                </button>
              </p>
            </div>
          </div>
        )}
      </div>

      {/* con */}
      {DoctorList.length > 0 && (
        <div className={style["context"]}>
          <div className={style["context-items"]}>
            {DoctorList.map((v, i) => (
              <div
                key={i}
                onClick={() => DoctorDetailClick(v)}
                className={style["names"]}
              >
                <img src={v.imagePic} alt="" />
                <span className={i == ind ? style["doctor_name"] : ""}>
                  {v.doctorName}
                </span>
              </div>
            ))}
          </div>
          <img
            src={nextIcon}
            alt=""
            className={style["nextIcon"]}
            onClick={() => nextPageClick()}
          />
        </div>
      )}
    </div>
  );
};

export default Index;
